//
//  TableVCVM.m
//  
//  jhf
//
//  Created by Mac on 2019/8/12.
//  Copyright © 2019 计海峰. All rights reserved.
//

#import "TableVCVM.h"
#import "Section.h"
#import "Row.h"
#import "RowInputBaseM.h"
#import "RowTitleBaseM.h"
#import <CooperSDK/CooperSDK.h>

@implementation TableVCVM

//MARK:-一般方法
// 初始化结束 属性未带过来
- (void)initDown; { }

// 配置结束 set get 结束
- (void)configDown; { }

// 一般用于固定rows
- (void)forRows; { }

// 默认是点击事件
- (void)actionTo:(id)model;{ }

- (NSIndexPath *)searchRow:(NSString *)actionKey; {
    if (!actionKey) {
        return nil;
    }
    // NSLog(@"%@", actionKey);
    __block NSIndexPath *indexPath;
    [self.sections enumerateObjectsUsingBlock:^(Section *  _Nonnull sec, NSUInteger idx, BOOL * _Nonnull secStop) {
        [sec.rows enumerateObjectsUsingBlock:^(Row * _Nonnull row, NSUInteger index, BOOL * _Nonnull stop) {
            if ([actionKey isEqualToString:row.model.action.key]) {
                indexPath = [NSIndexPath indexPathForRow:index inSection:idx];
                *stop = true;
                *secStop = true;
            }
        }];
    }];
    return indexPath;
}


- (BindModel *)searchBind:(NSString *)actionKey; {
    if (!actionKey) {
        return nil;
    }
    // NSLog(@"%@", actionKey);
    __block BindModel *bind = nil;
    [self.sections enumerateObjectsUsingBlock:^(Section *  _Nonnull sec, NSUInteger idx, BOOL * _Nonnull secStop) {
        [sec.rows enumerateObjectsUsingBlock:^(Row * _Nonnull row, NSUInteger index, BOOL * _Nonnull stop) {
            if ([actionKey isEqualToString:row.model.action.key]) {
                bind = row.model;
                *stop = true;
                *secStop = true;
            }
        }];
    }];
    return bind;
}

- (void)hiddeKeyboard {
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    UIViewController *vc = [window currentTopViewController];
    [vc.view endEditing:true];
}

//MARK: - row
- (Row *)genRowNeed:(RowNeedM *)needModel {
    Row *row = [self genRowCls:NSClassFromString(needModel.clsStr) model:[BindModel initWithBindey:self.bindKey model:needModel.info]];
    if (needModel.cellHeight > 0) {
        row.height = needModel.cellHeight;
    }
    if (needModel.bgColorHex) {
        row.bgColorHex = needModel.bgColorHex;
    }
    if (needModel.method) {
        row.method = needModel.method;
    }
    return row;
}

- (Row *)genRowId:(NSString *)identify; {
    return [self genRowCls:NSClassFromString(identify) model:nil];
}

- (Row *)genRowClassStr:(NSString *)clsStr model:(id)model {
    return [self genRowCls:NSClassFromString(clsStr) model:[BindModel initWithBindey:self.bindKey model:model]];
}

- (Row *)genRowClassStr:(NSString *)clsStr {
    return [self genRowCls:NSClassFromString(clsStr) model:nil];
}

- (Row *)genRowClass:(Class)cls {
    return  [self genRowCls:cls model:nil];
}

- (Row *)genRowClass:(Class)cls model:(id)model {
    return [self genRowCls:cls model:[BindModel initWithBindey:self.bindKey model:model]];
}

- (Row *)genRowCls:(Class)cls model:(BindModel *)model  {
    Row *row = [Row rowClass:cls model:model];
    row.bindKey = self.bindKey;
    return row;
}

//// 图片资源 返回 [files, names]
//- (NSArray *)imagesParams {
//    NSMutableArray *fileArray = [NSMutableArray array];
//    NSMutableArray *nameArray = [NSMutableArray array];
//    [self.sections enumerateObjectsUsingBlock:^(Section *section, NSUInteger sectionIdx, BOOL * _Nonnull sectionsStop) {
//        [section.rows enumerateObjectsUsingBlock:^(Row *row, NSUInteger rowIdx, BOOL * _Nonnull rowStop) {
//            if ([row modelClass:UploadImagesModel.class]) {
//                UploadImagesModel *info = (UploadImagesModel *)row.model.model;
//                [info.images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                    [fileArray addObject:obj];
//                    [nameArray addObject:info.key ?: @""];
//                }];
//            }
//        }];
//    }];
//    return @[fileArray, nameArray];
//}
//
//- (NSArray <ImagesModel *>*)imagesModelsParams {
//    NSMutableArray *tempArray = [NSMutableArray array];
//    [self.sections enumerateObjectsUsingBlock:^(Section *section, NSUInteger sectionIdx, BOOL * _Nonnull sectionsStop) {
//        [section.rows enumerateObjectsUsingBlock:^(Row *row, NSUInteger rowIdx, BOOL * _Nonnull rowStop) {
//            if ([row modelClass:UploadImagesModel.class]) {
//                UploadImagesModel *info = (UploadImagesModel *)row.model.model;
//                [info.imgModels enumerateObjectsUsingBlock:^(ImagesModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                    [tempArray addObject:obj];
//                }];
//            }
//        }];
//    }];
//    return tempArray;
//}

// MARK: - default rows
//- (Row *)lineRow; {
//    return [self genRowNeed:[RowManage lineRowHeight:8 bgColor:@"#f4f4f4"]];
//}
//
//- (Row *)lineRowHeight:(CGFloat)height {
//    return [self genRowNeed:[RowManage lineRowHeight:height bgColor:@"#f4f4f4"]];
//}

//MARK:-tableview
- (NSInteger)sectionsCount {
    return self.sections.count;
}

- (NSInteger)sectionCellCount:(NSInteger)section tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:section];
    return sec.rows.count;
}

- (UIView *)sectionFooterView:(NSInteger)section tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:section];
    return sec.footerView;
}

- (CGFloat)sectionFooterHeight:(NSInteger)section tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:section];
    return sec.footerHeight;
}

- (UIView *)sectionHeaderView:(NSInteger)section tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:section];
    return sec.headerView;
}

- (CGFloat)sectionHeaderHeight:(NSInteger)section tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:section];
    return sec.headerHeight;
}

- (CGFloat)cellHeight:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:indexPath.section];
    Row *row = [sec.rows objectAtIndex:indexPath.row];
    return row.height < 0 ? UITableViewAutomaticDimension : row.height;
}

- (UITableViewCell *)cell:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:indexPath.section];
    Row *row = [sec.rows objectAtIndex:indexPath.row];
    if (row) {
        return row.configCellBlock(indexPath, tableView);
    }
    return [[UITableViewCell alloc] init];
}

- (void)willDisplayCell:(NSIndexPath *)indexPath tableView:(UITableView *)tableView cell:(UITableViewCell *)cell {
    Section *sec = [self.sections objectAtIndex:indexPath.section];
    Row *row = [sec.rows objectAtIndex:indexPath.row];
//    if (row.cacheHeight && cell.frame.size.height != row.height) {
    if (row.autoCacheHeight && cell.frame.size.height != row.height) {
        row.height = cell.frame.size.height;
    }
}

- (void)select:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    Section *sec = [self.sections objectAtIndex:indexPath.section];
    Row *row = [sec.rows objectAtIndex:indexPath.row];
    if (row.method && row.method.length > 0) {
        NSString *realMethod = row.method;
        if (![row.method hasSuffix:@":"]) {
            realMethod = [NSString stringWithFormat:@"%@:", realMethod];
        }
        SEL sel = NSSelectorFromString(realMethod);
        if ([self respondsToSelector:sel]) {
            [self performSelectorOnMainThread:sel withObject:row.model waitUntilDone:false];
        }
    }else if ([row modelClass:RowTitleBaseM.class]) {
        RowTitleBaseM *titleBase = (RowTitleBaseM *)row.model.model;
        NSString *realMethod = titleBase.method;
        if (!realMethod && titleBase.methodFromKey && titleBase.dataKey) {
            realMethod = titleBase.dataKey;
        }
        if (![realMethod hasSuffix:@":"]) {
            realMethod = [NSString stringWithFormat:@"%@:", realMethod];
        }
        SEL sel = NSSelectorFromString(realMethod);
        if ([self respondsToSelector:sel]) {
            [self performSelectorOnMainThread:sel withObject:row.model waitUntilDone:false];
        }
    }
}

// MARK: - service
- (void)removeRow:(id)any{
    if (!any) {
        return;
    }
    NSString *key;
    if (any && [any isKindOfClass:NSString.class]) {
        key = (NSString *)any;
    }
    if (any && [any isKindOfClass:ActionModel.class]) {
        ActionModel *action = (ActionModel *)any;
        key = action.key;
    }
    NSIndexPath *indexPath = [self searchRow:key];
    if (indexPath) {
        Section *section = [self.sections objectAtIndex:indexPath.section];
        [section.rows removeObjectAtIndex:indexPath.row];
    }
}

- (void)removeSection:(id)any{
    if (!any) {
        return;
    }
    NSString *key;
    if (any && [any isKindOfClass:NSString.class]) {
        key = (NSString *)any;
    }
    if (any && [any isKindOfClass:ActionModel.class]) {
        ActionModel *action = (ActionModel *)any;
        key = action.key;
    }
    NSIndexPath *indexPath = [self searchRow:key];
    if (indexPath) {
        [self.sections removeObjectAtIndex:indexPath.section];
        [self.bindTargetTV reloadData];
    }
}

//MARK: - lazy
- (NSMutableArray <Section *>*)sections {
    if (!_sections) {
        _sections = [KVOMutableArray array];
    }
    return _sections;
}

- (KVOMutableArray <Row *>*)rows {
    if (!_rows) {
        _rows = [KVOMutableArray array];
        Section *sec = [Section sectionWithRows:_rows];
        sec.rows = _rows;
        [self.sections addObject:sec];
    }
    return _rows;
}

- (KVOMutableArray<Row *> *)tempRows {
    if (!_tempRows) {
        _tempRows = [KVOMutableArray array];
    }
    return _tempRows;
}

- (RACSubject *)transmitSignal {
    if (!_transmitSignal) {
        _transmitSignal = [RACSubject subject];
    }
    return _transmitSignal;
}

//MARK: - cell 上面操作
- (void)imageCellTap:(id)any; {
    NSLog(@"%@", any);
}

// MARK: - 一些服务啥啥的
- (UIViewController *)bindTargetVC; {
    if (self.block) {
        return self.block(@"self");
    }
    return nil;
}


- (UITableView *)bindTargetTV; {
    if (self.block) {
        return self.block(@"table");
    }
    return nil;
}

- (UIView *)bindTargetView; {
    if (self.block) {
        return self.block(@"view");
    }
    return nil;
}

- (NSArray *)bindTargetAll; {
    if (self.block) {
        return self.block(@"all");
    }
    return nil;
}


@end
